<template>
  <div>
    <div class="home_box">
      <div class="background">
        <img
          src="../../img/lake.png"
          style="width: 100%; height: 100%"
          alt=""
        />
      </div>
      <div height="80px" class="header">
        <div class="title">
          <img
            src="../../img/qiusuo.png"
            alt=""
            style="height: 46px; padding-top: 7px; float: left"
          />
          <div style="padding-left: 10px; float: right">统计&分析</div>
        </div>
      </div>
      <el-container class="mid_layout" style="height: 100%">
        <el-aside
          width="200px"
          style="background-color: rgba(255, 255, 255, 0.4)"
        >
          <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
            <el-radio-button :label="false">展开</el-radio-button>
            <el-radio-button :label="true">收起</el-radio-button>
          </el-radio-group>
          <el-menu
            default-active="1-4-1"
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            :collapse="isCollapse"
          >
            <!-- <el-submenu index="1">
              <template slot="title">
                <i class="el-icon-location"></i>
                <span slot="title">统计分析</span>
              </template>
              <el-menu-item-group>
                <el-menu-item index="1-1">默认报告</el-menu-item>
              </el-menu-item-group>
            </el-submenu> -->
            <!-- <el-menu-item index="2">
              <i class="el-icon-document"></i>
              <span slot="title">查看答卷</span>
            </el-menu-item> -->
            <!-- <el-menu-item index="3">
              <i class="el-icon-top-left"></i>
              <span slot="title">导出报告</span>
            </el-menu-item> -->
            <el-submenu index="2">
              <template slot="title">
                <i class="el-icon-download"></i>
                <span slot="title">导出报告</span>
              </template>
              <el-menu-item-group>
                <el-menu-item index="2-1" @click="outputPdf"
                  >导出统计分析报告pdf</el-menu-item
                >
                <el-menu-item index="2-2" @click="outputExcel"
                  >导出问卷数据excel</el-menu-item
                >
                <!-- <el-menu-item index="1-3">导出pdf</el-menu-item> -->
              </el-menu-item-group>
            </el-submenu>
            <el-menu-item index="4" @click="publish">
              <i class="el-icon-s-home"></i>
              <span slot="title">返回主页</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-main style="background-color: rgba(240, 240, 240, 0.4)">
          <div ref="reportToExport">
            <h2 style="text-align: center">{{ survey.title }}</h2>
            <template v-if="survey.type === 1">
              <h3 style="text-align: center">客观题分数排名</h3>
              <el-table
                :data="rankingList"
                style="width: 60%; margin: 0 auto"
                max-height="500"
              >
                <el-table-column type="index" label="排名" width="100">
                </el-table-column>
                <el-table-column prop="filler" label="用户名">
                </el-table-column>
                <el-table-column prop="score" label="客观题分数">
                </el-table-column>
              </el-table>
            </template>
            <div
              style="text-align: center"
              v-for="(question, index) of questionDataList"
              :key="question.id"
            >
              <h3>第{{ question.id + 1 }}题：{{ question.stem }}</h3>
              <template v-if="[0, 1, 2, 4, 5].includes(question.type)">
                <el-table
                  :data="question.tableData"
                  style="width: 60%; margin: 0 auto"
                  :show-summary="true"
                  max-height="500"
                >
                  <el-table-column prop="choice" label="选项" width="220">
                  </el-table-column>
                  <el-table-column prop="count" label="小计" width="220">
                  </el-table-column>
                  <el-table-column prop="ratio" label="比例"> </el-table-column>
                </el-table>
              </template>
              <template v-else>
                <el-table
                  :data="question.tableData"
                  style="width: 60%; margin: 0 auto"
                  max-height="500"
                >
                  <template v-if="question.type === 3">
                    <el-table-column prop="ansIndex" label="序号" :width="100">
                    </el-table-column>
                    <el-table-column prop="answer" label="答案">
                    </el-table-column>
                  </template>
                  <template v-else>
                    <el-table-column prop="ansIndex" label="序号" :width="100">
                    </el-table-column>
                    <el-table-column prop="longitude" label="经度" :width="100">
                    </el-table-column>
                    <el-table-column prop="latitude" label="纬度" :width="100">
                    </el-table-column>
                    <el-table-column prop="location" label="位置">
                    </el-table-column>
                  </template>
                </el-table>
              </template>
              <template v-if="[0, 1, 2, 4, 5].includes(question.type)">
                <div style="margin: 20px">
                  <el-radio
                    v-model="questionDataList[index].option.series[0].type"
                    label="bar"
                    @change="changeChartType(index)"
                    >柱状图</el-radio
                  >
                  <el-radio
                    v-model="questionDataList[index].option.series[0].type"
                    label="line"
                    @change="changeChartType(index)"
                    >折线图</el-radio
                  >
                  <el-radio
                    v-model="questionDataList[index].option.series[0].type"
                    label="pie"
                    @change="changeChartType(index)"
                    >饼状图</el-radio
                  >
                </div>
                <div
                  :id="'chart' + question.id"
                  style="width: 600px; height: 400px; margin: auto"
                ></div>
              </template>
            </div>
          </div>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rankingList: [
        {
          filler: "",
          score: -1,
        },
      ],
      // 侧边栏的属性
      isCollapse: false,
      // 问卷答卷收集统计
      questionDataList: [
        // 各题数据的列表，下面是一个全字段question样例，created后时会被替换
        {
          id: 0,
          stem: "题干部分",
          type: -1,
          chart: null,
          choices: [],
          counts: [],
          ans: [],
          keywords: [],
          tableData: [
            {
              choice: "2016-05-03",
              count: "3",
              ratio: "上海市普陀区金沙江路 1518 弄",
            },
            {
              choice: "2016-05-02",
              count: "4",
              ratio: "上海市普陀区金沙江路 1518 弄",
            },
          ],
          option: {
            // title: {
            //   text: "问题题干",
            // },
            legend: {
              data: ["人数"],
            },
            xAxis: {
              data: ["大一", "大二", "大三", "大四"],
            },
            yAxis: {},
            series: [
              {
                name: "人数",
                type: "bar",
                data: [5, 20, 36, 10],
              },
            ],
          },
        },
      ],
      survey: {},
    };
  },
  created() {
    console.log("============= created() in report.vue starts =============");
    this.survey = this.$store.state.surveyToAnalyze;
    console.log("survey got from $store:");
    console.log(this.survey);
    // 筛选选择类的题目
    let qs = this.survey.questions.filter((q) => {
      // return [0, 1, 2, 4, 5].includes(q.type);
      return true;
    });
    // 计算各个答卷人的排名
    this.rankingList = [];
    for (let i = 0; i < qs.length; i++) {
      const q = qs[i];
      if (q.statJson && JSON.parse(q.statJson).exam) {
        let exam = JSON.parse(q.statJson).exam;
        exam.forEach((record) => {
          let j = 0;
          for (; j < this.rankingList.length; j++) {
            const ranker = this.rankingList[j];
            if (ranker.filler === record.filler) {
              // 找到了对应的filler
              ranker.score += record.score;
              break;
            }
          }
          if (j === this.rankingList.length) {
            this.rankingList.push({
              filler: record.filler,
              score: record.score,
            });
          }
        });
      }
    }
    this.rankingList.sort(function (r1, r2) {
      return r2.score - r1.score;
    });
    this.survey.questions.sort((q1, q2) => q1.num - q2.num); // 确保num和元素索引一致
    console.log("all qs:");
    console.log(qs);
    let ret = []; // ret 会被赋给questionDataList，内含各题的数据
    qs.forEach((q) => {
      console.log("foreach starts: num: " + q.num + " type: " + q.type);
      if (q.type === 3) {
        //填空题
        if (!q.statJson) {
          // 处理0答卷数的情况
          console.log("no statJson for this q");
          q.statJson = JSON.stringify({
            ans: [],
          });
        }
        let ans = JSON.parse(q.statJson).ans;
        let toPush = {
          id: q.num, // 题号
          stem: q.stem,
          type: q.type,
          ans: ans,
          tableData: [], // 用于填充表格的数据，包括
        };
        for (let i = 0; i < ans.length; i++) {
          const a = ans[i];
          toPush.tableData.push({
            ansIndex: i + 1,
            answer: a,
          });
        }
        // let allAns = ans.join(',')
        // toPush.keywords = this.$jieba.extract(allAns, 10)
        // console.log(toPush.keywords);
        ret.push(toPush);
      } else if (q.type === 6) {
        // 定位题
        if (!q.statJson) {
          // 处理0答卷数的情况
          console.log("no statJson for this q");
          q.statJson = JSON.stringify({
            ans: [],
          });
        }
        let ans = JSON.parse(q.statJson).ans;
        let toPush = {
          id: q.num, // 题号
          stem: q.stem,
          type: q.type,
          tableData: [], // 用于填充表格的数据，包括
        };
        for (let i = 0; i < ans.length; i++) {
          const a = ans[i];
          toPush.tableData.push({
            ansIndex: i + 1,
            longitude: a[0].toFixed(2) + "°E", // 就这样吧别的不管了
            latitude: a[1].toFixed(2) + "°N",
            location: a[2],
          });
        }
        ret.push(toPush);
      } else {
        // 选择类的题
        let choices = [];
        let counts = [];
        if (q.type === 2) {
          // 评分题
          choices = ["⭐", "⭐⭐", "⭐⭐⭐", "⭐⭐⭐⭐", "⭐⭐⭐⭐⭐"];
          console.log("choices for rank are now ⭐s");
        } else {
          //其它选择类的题
          choices = JSON.parse(q.propJson).options;
        }
        console.log("choices:");
        console.log(choices);
        if (!q.statJson) {
          // 处理0答卷数的情况
          console.log("no statJson for this q");
          let zeros = Array(choices.length).fill(0); // 每个选项的选择数均为0
          q.statJson = JSON.stringify({
            num: zeros,
          });
        }
        counts = JSON.parse(q.statJson).num;
        if (counts.length === 0) {
          // 处理0答卷数的情况
          console.log("no statJson for this q");
          counts = Array(choices.length).fill(0);
        }
        console.log("counts:");
        console.log(counts);
        let toPush = {
          id: q.num, // 题号
          stem: q.stem,
          type: q.type,
          tableData: [], // 用于填充表格的数据，包括choice、count、ratio
          choices: choices,
          counts: counts,
          option: {
            // title: {
            //   text: q.stem,
            // },
            legend: {
              // 图例
              data: [],
            },
            xAxis: {
              data: choices,
              axisLabel: {
                interval: 0,
                formatter: function (value) {
                  var ret = ""; //拼接加\n返回的类目项
                  var maxLength = parseInt(30 / choices.length); //每项显示文字个数
                  console.log("maxLength on xAxis: " + maxLength);
                  var valLength = value.length; //X轴类目项的文字个数
                  var rowN = Math.ceil(valLength / maxLength); //类目项需要换行的行数
                  if (rowN > 1) {
                    //如果类目项的文字大于5,
                    for (var i = 0; i < rowN; i++) {
                      var temp = ""; //每次截取的字符串
                      var start = i * maxLength; //开始截取的位置
                      var end = start + maxLength; //结束截取的位置
                      //这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
                      temp = value.substring(start, end) + "\n";
                      ret += temp; //凭借最终的字符串
                    }
                    return ret;
                  } else {
                    return value;
                  }
                },
              },
            },
            yAxis: {},
            series: [
              {
                name: "选项人数",
                type: "bar",
                data: counts,
              },
            ],
          },
        };
        for (let index = 0; index < choices.length; index++) {
          // 填充tableData
          const o = choices[index];
          const c = counts[index];
          let ratio_float = c / counts.reduce((a, b) => a + b, 0) || 0; // 逻辑或的作用是，如果前面的表达式为NaN（除以0导致的），返回0，否则返回原值
          toPush.tableData.push({
            choice: o,
            count: c,
            ratio: (ratio_float * 100).toFixed(2) + "%",
          });
        }
        ret.push(toPush);
      }
    });
    this.questionDataList = ret;
  },
  // computed: {
  //   questionDataList() {},
  // },
  mounted() {
    this.drawChart();
  },
  methods: {
    // 侧边栏的两个方法
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    outputPdf() {
      this.$message("统计分析报告生成中");
      this.$PDFSave(this.$refs.reportToExport, this.survey.title);
    },
    drawChart() {
      this.questionDataList.forEach((question) => {
        if (question.type === 3) {
          // 填空题画词云

          return;
        } else if (question.type === 6) {
          // 定位题不报错
          return
        }
        let myChart = null;
        try {
          myChart = this.$echarts.init(
            document.getElementById("chart" + question.id)
          );
          myChart.setOption(question.option);
        } catch (error) {
          console.error(
            "******question.id: " + question.id + " error " + error + "******"
          );
        }
        question.chart = myChart;
      });
    },
    changeChartType(index) {
      let question = this.questionDataList[index];
      // 目前 option 里面只有 type 改变了
      let newType = question.option.series[0].type;
      let isPie = newType === "pie";
      // 下面 2 行用于调整坐标轴是否可见
      question.option.xAxis.show = !isPie;
      question.option.yAxis.show = !isPie;
      // 给pie添加图例，其他不添加
      question.option.legend.data = isPie ? question.choices : [];
      // pie和其他图的data格式不同，要修改
      let newData = [];
      if (isPie) {
        for (let i = 0; i < question.choices.length; i++) {
          newData.push({
            name: question.choices[i],
            value: question.counts[i],
          });
        }
      } else {
        newData = question.counts;
      }
      question.option.series[0].data = newData;
      // 提交option改动
      question.chart.setOption(question.option, true);
      console.log("new option:");
      console.log(question.option);
    },
    publish(event) {
      console.log("publish");
      this.$router.push("publish");
    },
    outputExcel() {
      this.$http
        .get("/stat/survey/export?sid=" + this.survey.sid, {
          responseType: "arraybuffer",
        })
        .then((res) => {
          // console.log(res.data);
          this.downloadContent(res.data, "导出数据");
        });
    },
    clone(ojb) {
      return JSON.parse(JSON.stringify(ojb));
    },
    downloadContent(value, name) {
      const link = document.createElement("a");
      const blob = new Blob([value], { type: "application/vnd.ms-excel" });
      const url = window.URL.createObjectURL(blob);
      link.href = url;
      link.download = name + ".xls";
      link.click();
      window.URL.revokeObjectURL(url);
    },
  },
};
</script>

<style lang="less" scoped>
.home_box {
  height: 100%;
  width: 100%;
  min-width: 1600px;
}
.background {
  // background-image: url("../../img/1.jpg");
  /* 相对于视口固定 */
  // background-attachment: fixed;
  // background-size: cover;
  // background-position: 50% 50%;
  // position: relative;
  // text-align: center;
  // overflow: hidden;
  background-size: cover;
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: -1;
}
// 页面头部（最上面一栏）
.header {
  background-color: rgba(240, 240, 240, 0.8);
  height: 60px;
  position: relative;
}
.mid_layout {
  width: 75%;
  height: 100%;
  margin: 0 auto;
  background-color: rgba(255, 255, 255, 0.6);
}
.title {
  display: block;
  float: left;
  font-size: 34px;
  font-weight: 600;
  font-family: "SimSun";
  line-height: 60px;
  margin-left: 10px;
}
.card:hover {
  background-color: #f0f0f0;
}
.el-aside {
  background-color: rgba(255, 255, 255, 0.4);
}

// 侧边栏高度
.el-menu-vertical-demo[data-v-2f693578]:not(.el-menu--collapse) {
  width: 200px;
  min-height: 93%;
}
/deep/ .el-radio-group {
  margin-bottom: 20px;
  margin-top: 20px;
  margin-left: 40px;
  width: 80%;
  height: 50px;
}
/deep/ .el-menu {
  border-right: solid 1px #e6e6e6;
  list-style: none;
  position: relative;
  margin: 0;
  padding-left: 0;
  background-color: rgba(255, 255, 255, 0.2);
}

// 表格的表头字体和横线
/deep/ .el-table td,
.el-table th.is-leaf {
  border-bottom: 1px solid #7180a2;
}
/deep/ .el-table thead {
  color: #4376dd;
  font-weight: 500;
}

// 侧边栏
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
  font-size: 16px;
}
</style>